package com.education.ai.service.impl;

import com.education.ai.dao.KnowledgePointDao;
import com.education.ai.entity.KnowledgePoint;
import com.education.ai.service.KnowledgePointService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 知识点服务实现类
 */
@Service
public class KnowledgePointServiceImpl implements KnowledgePointService {

    @Autowired
    private KnowledgePointDao knowledgePointDao;

    @Override
    public List<KnowledgePoint> getAllKnowledgePoints() {
        return knowledgePointDao.findAll();
    }

    @Override
    public Optional<KnowledgePoint> getKnowledgePointById(Long id) {
        return knowledgePointDao.findById(id);
    }

    @Override
    public List<KnowledgePoint> getKnowledgePointsBySubject(String subject) {
        return knowledgePointDao.findBySubject(subject);
    }

    @Override
    public List<KnowledgePoint> getKnowledgePointsBySubjectAndGrade(String subject, String grade) {
        return knowledgePointDao.findBySubjectAndGrade(subject, grade);
    }

    @Override
    public KnowledgePoint saveKnowledgePoint(KnowledgePoint knowledgePoint) {
        return knowledgePointDao.save(knowledgePoint);
    }

    @Override
    public void deleteKnowledgePoint(Long id) {
        knowledgePointDao.deleteById(id);
    }

    @Override
    public Map<Long, List<KnowledgePoint>> getKnowledgeHierarchy(String subject) {
        // 获取指定学科的所有知识点
        List<KnowledgePoint> allPoints = knowledgePointDao.findBySubject(subject);
        
        // 按父ID分组
        Map<Long, List<KnowledgePoint>> hierarchyMap = new HashMap<>();
        
        // 获取顶级知识点（parentId为null的）
        List<KnowledgePoint> rootPoints = allPoints.stream()
                .filter(point -> point.getParentId() == null)
                .collect(Collectors.toList());
        
        // 添加顶级节点
        hierarchyMap.put(0L, rootPoints);
        
        // 分组其他子节点
        for (KnowledgePoint point : allPoints) {
            if (point.getParentId() != null) {
                if (!hierarchyMap.containsKey(point.getParentId())) {
                    hierarchyMap.put(point.getParentId(), new ArrayList<>());
                }
                hierarchyMap.get(point.getParentId()).add(point);
            }
        }
        
        return hierarchyMap;
    }

    @Override
    public List<KnowledgePoint> searchKnowledgePoints(String name, String subject) {
        // 使用名称模糊查询并且过滤学科
        List<KnowledgePoint> results = knowledgePointDao.findByNameContaining(name);
        return results.stream()
                .filter(point -> subject == null || subject.isEmpty() || subject.equals(point.getSubject()))
                .collect(Collectors.toList());
    }

    @Override
    public List<KnowledgePoint> getChildKnowledgePoints(Long parentId) {
        return knowledgePointDao.findByParentId(parentId);
    }
} 